var Workport = Workport || {};

Workport.TagFunc = (function(){
	var responseSuccessCode = ['WP1001', 'WP1003', 'WP1005'], timer;

	function tagsInputEvent (_tagsElem, _val, _showLoaderFunc, _hideLoaderFunc) {
        if (!_val) {
            clearTimeout(timer);
            return;
        }
        clearTimeout(timer);
        timer = setTimeout(function () {
        	var tagsDataList, val = _val.split(',');
	        val = val[val.length - 1];

	        if (val.length == 0) {return;}

	        _showLoaderFunc();
	        //get data
        	var tmp = $.param({key:val}).substring(4);
            Workport.TagAPI.getTag(function (data) {
            	_hideLoaderFunc();
            	if (data) {
	                if ($.inArray(data.ResponseCode, responseSuccessCode) == -1) {
	                    Workport.utils.alertMsg("", data.ResponseMessage, function(_data){});
	                } else {
	                    tagsDataList = new Array();
	                    if (data.Tags != null) {
	                        for (var i = 0; i < data.Tags.length; i++) {
	                            tagsDataList.push({"name": data.Tags[i].Tag});
	                        }
	                        
	                        _tagsElem.data("kendoAutoComplete").setDataSource(tagsDataList);
	                        _tagsElem.data("kendoAutoComplete").search(val);
	                    }
	                }
            	}
            }, {"key":tmp, "ps":50, "pn":1});
        }, 2000);
    };

    return {
    	setTagsAutoComplete : function (_tagsElem, _showLoaderFunc, _hideLoaderFunc) {
	        _tagsElem.kendoAutoComplete({
	            dataTextField: "name",
	            filter: "contains",
	            separator: ",",
	            delay: 1500,
	            close: function () {
	                _tagsElem.data("kendoAutoComplete").setDataSource([]);
	            }
	        });

	        _tagsElem.unbind('input').bind('input', function () {
                tagsInputEvent(_tagsElem, $.trim(_tagsElem.val()), _showLoaderFunc, _hideLoaderFunc);
            });
		},
		stopSearchTags : function () {
			clearTimeout(timer);
		}
	}
})();